import { useEffect, useRef, useState } from 'react';
import { LIMIT } from '@/constants/pageConstant.js';
import { Card, Flex, Form, Input, InputNumber, Select, Tag } from 'antd';
import { CustomPage, CustomTable } from '@/components/index.jsx';
import { SPACE } from '@/constants/themeConstant.js';
import SearchForm from '@/components/SearchForm/index.jsx';
import { OperationLogApi } from '@/api/operation-log/api.js';
import StringUtil from '@/utils/string.js';

export default function OperationLogManage() {
  // 表格
  const tableRef = useRef();
  // 搜索条件
  const [searchQuery, setSearchQuery] = useState();

  useEffect(() => {
    if (searchQuery) {
      tableRef.current?.request();
    }
  }, [searchQuery]);

  // 请求数据
  async function getData(options) {
    // 解构条件
    const { pagination, sorter } = options;
    // 页码
    const pageNo = pagination?.current || 1;
    // 页大小
    const pageSize = pagination?.pageSize || LIMIT;
    // 排序字段
    const sortField = StringUtil.toSnakeCase(sorter?.field);
    // 排序方式
    const sortOrder = sorter?.order === 'ascend';
    // 请求数据
    const { code, data } = await OperationLogApi.getList(
      pageNo,
      pageSize,
      searchQuery,
      sortField,
      sortOrder
    );
    const { list, total } = data;
    return Promise.resolve({
      data: list,
      success: code === 0,
      total: total
    });
  }

  return (
    <CustomPage>
      <Card>
        <Flex vertical gap={SPACE}>
          {renderToolbar()}
          <CustomTable
            ref={tableRef}
            rowKey="id"
            title="操作日志列表"
            optionsWidth={45}
            columns={getColumns()}
            request={getData}
          />
        </Flex>
      </Card>
    </CustomPage>
  );

  // 渲染工具栏
  function renderToolbar() {
    const width = 150;
    return (
      <>
        <SearchForm
          onSearch={(values) => {
            tableRef.current?.setPageNo(1);
            setSearchQuery(values);
          }}
          formItems={
            <>
              <Form.Item label="日志ID" name="id">
                <InputNumber min={1} placeholder="请输入日志ID" style={{ width: width }} />
              </Form.Item>
              <Form.Item label="追踪ID" name="traceId">
                <Input placeholder="请输入追踪ID" style={{ width: width * 2 }} />
              </Form.Item>
              <Form.Item label="操作者ID" name="userId">
                <Input placeholder="请输入操作者ID" style={{ width: width }} />
              </Form.Item>
              <Form.Item label="请求类型" name="type">
                <Input placeholder="请输入请求类型" style={{ width: width }} />
              </Form.Item>
              <Form.Item label="操作标题" name="title">
                <Input placeholder="请输入操作标题" style={{ width: width * 2 }} />
              </Form.Item>
              <Form.Item label="请求IP" name="ip">
                <Input placeholder="请输入请求IP" style={{ width: width }} />
              </Form.Item>
              <Form.Item label="执行状态" name="status">
                <Select
                  style={{ width: width }}
                  placeholder="请选择执行状态"
                  options={[
                    { label: '成功', value: '1' },
                    { label: '失败', value: '2' }
                  ]}
                />
              </Form.Item>
              <Form.Item label="请求接口" name="url">
                <Input placeholder="请输入请求接口" style={{ width: width * 2 }} />
              </Form.Item>
              <Form.Item label="请求方法" name="method">
                <Input placeholder="请输入请求方法" style={{ width: width * 3 }} />
              </Form.Item>
            </>
          }
        />
      </>
    );
  }

  // 表格列
  function getColumns() {
    return [
      {
        title: '日志ID',
        dataIndex: 'id',
        key: 'id',
        sorter: true
      },
      { title: '追踪ID', dataIndex: 'traceId', key: 'traceId' },
      {
        title: '操作者ID',
        dataIndex: 'userId',
        key: 'userId'
      },
      {
        title: '请求类型',
        dataIndex: 'type',
        key: 'type'
      },
      {
        title: '操作标题',
        dataIndex: 'title',
        key: 'title'
      },
      {
        title: '请求IP',
        dataIndex: 'ip',
        key: 'ip'
      },
      {
        title: '请求接口',
        dataIndex: 'url',
        key: 'url'
      },
      {
        title: '请求方法',
        dataIndex: 'method',
        key: 'method'
      },
      {
        title: '请求参数',
        dataIndex: 'args',
        key: 'args'
      },
      {
        title: '错误信息',
        dataIndex: 'error',
        key: 'error'
      },
      {
        title: '执行状态',
        dataIndex: 'status',
        key: 'status',
        render: (text) => {
          return text === '1' ? <Tag color="green">成功</Tag> : <Tag color="red">失败</Tag>;
        }
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        key: 'startTime'
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        key: 'endTime'
      },
      {
        title: '执行耗时',
        dataIndex: 'taskTime',
        key: 'taskTime',
        sorter: true,
        render: (text) => {
          return text + 'ms';
        }
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        sorter: true
      }
    ];
  }
}
